package UDPProgramming.example01;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author lhn
 * @date 2024-04-25 22:18
 * UDP接收端
 */

public class UDPReceiverA {
    public static void main(String[] args) throws IOException {
        //创建一个datagramSocket对象在端口9999
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        //构建datagramPacket对象用于接收数据
        byte[] buffer = new byte[64 * 1024];    //UDP一个数据包最大64K
        DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
        //通过网络传输的 datagramPacket 接收数据
        System.out.println("等待接收数据中...");
        datagramSocket.receive(datagramPacket); //没有接收到数据包会阻塞

        //可以把 datagramPacket 进行拆包，取出里面的内容
        int length = datagramPacket.getLength();
        byte[] data = datagramPacket.getData();
        System.out.println("A端收到消息--"+new String(data, 0, length));

        byte[] sendData = "好的，明天见".getBytes();
        datagramPacket = new DatagramPacket(sendData, sendData.length,
                InetAddress.getByName("192.168.123.86"), 9998);
        datagramSocket.send(datagramPacket);
        System.out.println("发送完成");

        //释放资源
        datagramSocket.close();
        System.out.println("A端关闭");
    }
}
